package jee.boot.module.bpm.service;

import jee.boot.common.basic.CrudService;
import jee.boot.common.utils.MapUtils;
import jee.boot.entity.bpm.BusTableRel;
import jee.boot.entity.bpm.BusinessTable;
import jee.boot.entity.system.Filter;
import jee.boot.module.bpm.dao.BusinessObjectDao;
import jee.boot.entity.bpm.BusinessObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 业务对象
 */
@Service
public class BusinessObjectService extends CrudService<BusinessObjectDao, BusinessObject> {
    @Autowired
    private BusinessTableService businessTableService;
    /**
     * 根据名称查询
     * @param object
     * @return
     */
    public BusinessObject getByName(BusinessObject object) {
        object.addFilter(new Filter("name","=",object.getName()));
        List<BusinessObject> list = dao.findList(object);
        if(list!=null && !list.isEmpty()){
            return list.get(0);
        }
        return null;
    }

    @Override
    public BusinessObject get(BusinessObject entity) {
        BusinessObject businessObject = super.get(entity);
        loadCompleteData(businessObject);
        return businessObject;
    }

    @Override
    public void save(BusinessObject entity) {
        uniquenessCheck(entity,"name");
        super.save(entity);
    }

    @Override
    public void update(BusinessObject entity) {
        uniquenessCheck(entity,"name");
        super.update(entity);
    }
    public void loadTable( Map<String,Object> relation){
        BusinessTable businessTable = MapUtils.toBean(relation.get("businessTable"),BusinessTable.class);
        // 重载主表的完整信息
        relation.put("businessTable",businessTableService.get(businessTable));
        List<Map<String,Object>> children = MapUtils.toBean(relation.get("children"),List.class);
        // 递归重载子表关系中的表结构
        if(children!=null && !children.isEmpty()){
            for(Map<String,Object> rel :children){
                loadTable(rel);
            }
            relation.put("children",children);
        }
    }

    public void loadCompleteData(BusinessObject businessObject) {
        // 对象关系
//        BusTableRel relation = businessObject.getRelation();
        Map<String,Object> relation = businessObject.getRelationMap();
        // 根据关系重载表数据
        loadTable(relation);
        businessObject.configRelationMap(relation);
    }
}
